import { AssetManager, Node, Prefab, UIComponent, instantiate } from "cc";
import { Logger } from "./Logger";
import { ResourceManager } from "./ResourceManager";
import { UI_Cache_Type, UI_Config } from "./UI_Config";
import ViewBase from "./ViewBase";
import { EventManager } from "./EventManager";
import { EngineConfig } from "./EngineConfig";
import { ViewCheck } from "../view/ViewCheck";
import { ViewTip } from "../view/ViewTip";

export class UIManager {

    public static instance: UIManager = new UIManager();

    //单例的面板
    private singleList: Map<UI_Config, ViewBase> = new Map<UI_Config, ViewBase>();
    //正在展示的界面
    private showList: Map<number, ViewBase> = new Map<number, ViewBase>();

    private onlyId: number = 0;

    private maskLayer: Node; //灰色底板，防止点击
    /**基础层 */
    private uiContainer: Node;

    private loadingIcon: Node; //转圈圈

    public init(uiRoot: Node) {
        EventManager.instance.off(EngineConfig.Event_Type.Event_CloseView, this.closeView, this)
        EventManager.instance.on(EngineConfig.Event_Type.Event_CloseView, this.closeView, this)
        this.maskLayer = uiRoot.getChildByName("maskLayer");
        this.maskLayer.active = false;
        this.uiContainer = uiRoot.getChildByName("uiContainer");
        this.loadingIcon = uiRoot.getChildByName("loadingIcon");
        this.hideLoadingIcon()
    }

    public showLoadingIcon(isShowIcon: boolean = true) {
        this.loadingIcon.active = isShowIcon;
        this.loadingIcon.getChildByName("icon").active = isShowIcon;
    }

    public hideLoadingIcon() {
        this.loadingIcon.active = false;
    }

    /**
     * 展示 view
     * @param uiConfig 
     * @param showLoading 
     * @param callback 
     * @param optionalParams 
     * @returns 
     */
    public showView(uiConfig: UI_Config, showLoading: boolean = true, callback?: Function, ...optionalParams: any[]) {
        Logger.log("showView==", uiConfig)
        if (!uiConfig) {
            Logger.error("showView=uiConfig 为空=");
            return;
        }
        if (showLoading) {
            this.showLoadingIcon();
        }
        if (this.singleList.has(uiConfig)) {
            for (let i = 0; i < this.uiContainer.children.length; i++) {
                this.uiContainer.children[i].setSiblingIndex(i);
            }
            let view: ViewBase = this.singleList.get(uiConfig);
            this.showList.set(view.onlyId, view);
            view.onInitBase(this.maskLayer, uiConfig, ...optionalParams);
            view.node.active = true;
            view.node.setSiblingIndex(view.node.parent.children.length)
            if (showLoading) {
                this.hideLoadingIcon();
            }
            callback && callback(view);
        }
        else {
            if (ResourceManager.instance.bundleMap.has(uiConfig.bundleName)) {
                this.loadView(uiConfig, (prefab: Prefab) => {
                    let view: ViewBase = this.createView(prefab, uiConfig, ...optionalParams);
                    if (showLoading) {
                        this.hideLoadingIcon();
                    }
                    callback && callback(view);
                })
            } else {
                // 没有 bundle 加载 bundle
                ResourceManager.instance.loadBundle(uiConfig.bundleName, () => {
                    this.loadView(uiConfig, (prefab: Prefab) => {
                        let view: ViewBase = this.createView(prefab, uiConfig, ...optionalParams);
                        if (showLoading) {
                            this.hideLoadingIcon();
                        }
                        callback && callback(view);
                    })
                })
            }
        }
    }

    /**
     * 加载 view
     * @param uiConfig 
     * @param callback 
     */
    public loadView(uiConfig: UI_Config, callback?: Function) {
        let bundle: AssetManager.Bundle = ResourceManager.instance.bundleMap.get(uiConfig.bundleName)
        ResourceManager.instance.load(uiConfig.path, bundle, null, (prefab: Prefab) => {
            if (prefab instanceof Prefab) {
                callback && callback(prefab)
            } else {
                Logger.error("showView 加载失败", uiConfig, bundle, prefab)
            }
        });
    }

    /**
     * 创建 view
     * @param prefab 
     * @param uiConfig 
     * @param optionalParams 
     * @returns 
     */
    private createView(prefab: Prefab, uiConfig: UI_Config, ...optionalParams): ViewBase {
        for (let i = 0; i < this.uiContainer.children.length; i++) {
            this.uiContainer.children[i].setSiblingIndex(i);
        }
        let item: Node = instantiate(prefab);
        let view: ViewBase = item.getComponent(ViewBase);
        if (!view) {
            Logger.error("showView  展示失败,没有添加ViewBase组件", uiConfig)
        } else {
            view.onlyId = this.onlyId++;
            item.setPosition(0, 0);
            view.onInitBase(this.maskLayer, uiConfig, ...optionalParams);
            item.parent = this.uiContainer;
            item.active = true
            view.node.setSiblingIndex(view.node.parent.children.length)
            this.showList.set(view.onlyId, view);
            if (view.uiConfig.isSingle) { //单例才缓存起来
                this.singleList.set(view.uiConfig, view);
            }
        }
        return view
    }

    /**
     * 关闭 view
     * @param view 
     */
    public closeView(view: ViewBase) {
        Logger.log("closeView=", view)
        view.closeView()
        this.showList.delete(view.onlyId);
        if (view.uiConfig.cacheType == UI_Cache_Type.noCache) {
            if (view.uiConfig.isSingle) {
                this.singleList.delete(view.uiConfig);
            }
            if (view.uiConfig.cacheType == UI_Cache_Type.noCache) {
                ResourceManager.instance.releaseByUiConfig(view.uiConfig);
            }
        }
    }

    /**
     * 根据 Ui配置关闭界面
     */
    public closeViewByUiConfig(uiConfig: UI_Config) {
        this.showList.forEach((value: ViewBase, id: number) => {
            if (value.uiConfig == uiConfig) {
                this.closeView(value);
            }
        });
    }

    //除了当前 view 全部关闭 
    public closeExceptView(uiConfig: UI_Config) {
        this.showList.forEach((value: ViewBase, id: number) => {
            if (value.uiConfig != uiConfig) {
                value.closeView()
            }
        });
    }

    /**
     * 关闭所有界面
     */
    public closeAllView() {
        this.showList.forEach((value: ViewBase, id: number) => {
            value.closeView();
        });
        this.showList.clear();
        this.hideLoadingIcon();
    }


    /**
     * toast 提示
     * @param tipsStr  提示内容
     * @param tipType 提示类型，详情看TipView
     */
    public showTip(tipsStr: string, tipType: number = ViewTip.TipType.Success) {
        UIManager.instance.showView(ViewTip.uiConfig, true, null, tipsStr, tipType);
    }

    /**
     * 打开提示框 
     * @param tips 
     * @param callback 
     * @param dialogType 
     */
    public showCheck(tips: string, callback: Function = null,
        dialogType: number = ViewCheck.Dialog_Type.All) {
        UIManager.instance.showView(ViewCheck.uiConfig, true, null, tips, dialogType, callback);
    }

}